package com.itheima.demo8;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class Test {
    public static void main(String[] args) throws IOException, IllegalAccessException {

        Student s = new Student("小N","女",18,1,"巧克力城堡");
        Teacher t = new Teacher("hanser",10000);

        saveObject(s);
//        saveObject(t);

    }

    //把对象里面的所有的成员变量名和值保存在本地文件
    public static void saveObject(Object obj) throws IOException, IllegalAccessException {
        //1.获取字节码文件的对象
        Class clazz = obj.getClass();

        //2.创建IO流
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        //3.获取所有的成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取成员变量的名字
            String name = field.getName();
            //获取成员变量的值
            Object o = field.get(obj);
            //写出数据
            bw.write(name + "=" + o);
            bw.newLine();
            System.out.println(name + "=" + o);
        }

        bw.close();

    }
}
